package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContants;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author:YZN
 * @date:2022/12/31
 * @description:
 */
@Service
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    @Transactional
    public R addDish(DishDto dishDto) {
        //todo 参数校验
        if (null == dishDto) {
            return R.error("参数异常");
        }
        //todo 保存菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);

        dishMapper.insert(dish);


        //todo 保存口味信息
        dishDto.getFlavors().forEach(item -> {
            item.setDishId(dish.getId());
            dishFlavorMapper.insert(item);
        });
        redisTemplate.delete(BaseContants.DISH_SUFFIX + dishDto.getCategoryId());
        return R.success("添加菜品成功");
    }

    @Override
    public R findPage(Integer page, Integer pageSize, String name) {
        //todo 参数校验
        if (page <= 0 || pageSize <= 0) {
            return R.error("参数错误");
        }
        //todo 进行分页条件查询
        Page<Dish> pageDish = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(name), Dish::getName, name);
        dishMapper.selectPage(pageDish, queryWrapper);
        //todo 菜品封装成DishVo对象,并且查询分类名字
        Page<DishDto> dishVoPage = new Page<>();
        BeanUtils.copyProperties(pageDish, dishVoPage);

        List<DishDto> collect = pageDish.getRecords().stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Category category = categoryMapper.selectById(item.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());

        dishVoPage.setRecords(collect);

        return R.success(dishVoPage);
    }

    @Override
    public R findById(Long id) {
        //todo 参数校验
        if (null == id) {
            return R.error("参数错误");
        }
        //todo 根据id查询出菜品信息
        Dish dish = dishMapper.selectById(id);
        //todo 根据菜品id查询出菜品口味集合
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(queryWrapper);
        //todo 封装参数返回
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(dishFlavors);

        return R.success(dishDto);
    }

    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    @Override
    @Transactional
    public R modify(DishDto dishDto) {
        //todo 参数校验
        if (null == dishDto) {
            return R.error("参数错误");
        }
        //todo 修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);
        dishMapper.updateById(dish);

        //todo 修改口味信息(多表修改 先删后增)
        //todo 删除口味信息
        LambdaUpdateWrapper<DishFlavor> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DishFlavor::getDishId, dish.getId());
        dishFlavorMapper.delete(updateWrapper);
        //todo 新增口味信息

        dishDto.getFlavors().stream().forEach(item -> {
            item.setDishId(dish.getId());
            item.setId(null);
            dishFlavorMapper.insert(item);
        });

        return R.success("修改成功");
    }

    @Cacheable(value = "dishCache",key = "#categoryId",unless = "#result.data==null")
    @Override
    public R list(Long categoryId) {
        //todo 参数校验
        if (null == categoryId) {
            return R.error("参数错误");
        }
        //如果redis中有 直接从redis中取
        //todo 根据categoryId来查询菜品
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        List<Dish> dishList = dishMapper.selectList(queryWrapper);
        List<DishDto> dishDtoList = dishList.stream().map(d -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(d, dishDto);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, d.getId()));
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    @CacheEvict(value = "dishCache",allEntries = true)
    @Override
    public R delete(Long[] ids) {
        //todo 参数校验
        if (null == ids) {
            return R.error("参数错误");
        }
        //todo 批量删除菜品
        Arrays.stream(ids).forEach(c -> {
            Dish dish = dishMapper.selectById(c);
            dishMapper.deleteById(c);
        });

        return R.success("删除成功");
    }

    @Override
    public R status(Integer type, Long[] ids) {
        //todo 参数校验
        if (null == ids || null == type) {
            return R.error("参数错误");
        }
        //todo 判断是停售还是起售
        if (type == 1) {
            //起售
            Arrays.stream(ids).forEach(c -> {
                Dish dish = dishMapper.selectById(c);
                dish.setStatus(1);
                dishMapper.updateById(dish);
            });
            return R.success("起售成功");
        } else if (type == 0) {
            //停售
            Arrays.stream(ids).forEach(c -> {
                Dish dish = dishMapper.selectById(c);
                dish.setStatus(0);
                dishMapper.updateById(dish);
            });
            return R.success("停售成功");
        }
        return R.error("未知错误");
    }
}
